import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email import encoders
from email.mime.text import MIMEText

# 邮件发送方和接收方信息
sender = 'asdfzxcvqwer123a@126.com'
receiver = 'asdfzxcvqwer123a@126.com'
password = 'HRBRRZQTAXWIKKHM'  # 126邮箱的SMTP服务密码
smtpserver = 'smtp.126.com'

# 创建一个带附件的邮件消息对象
msg = MIMEMultipart()
msg['From'] = sender
msg['To'] = receiver
msg['Subject'] = "这是来自126邮箱的带有附件的邮件"

# 邮件正文内容
body = "这是邮件正文，附件是一个xlsx文件。"
msg.attach(MIMEText(body, 'plain'))

# 附件文件名和路径
filename = "output/5 月/2024-07-31-1 [招标数据].xlsx"
attachment = open(filename, "rb")

# 添加附件到邮件消息中
part = MIMEBase('application', 'vnd.openxmlformats-officedocument.spreadsheetml.sheet')
part.set_payload((attachment).read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename= %s" % filename)

# 将附件添加到邮件中
msg.attach(part)

try:
    smtp = smtplib.SMTP()
    smtp.connect(smtpserver, 25)  # 连接SMTP服务器，25为SMTP端口号
    smtp.login(sender, password)  # 登录邮箱，注意这里是SMTP服务密码
    smtp.sendmail(sender, receiver, msg.as_string())  # 发送邮件
    smtp.quit()
    print("邮件发送成功！")
except smtplib.SMTPException as e:
    print("Error: 无法发送邮件", e)
finally:
    attachment.close()